﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.IO;
using System.Configuration;
using System.Text.RegularExpressions;

namespace FileRenamer
{
    public partial class MainForm : Form
    {
        FrequentReplacements frequentReplacements = new FrequentReplacements();
        public MainForm()
        {
            InitializeComponent();
        }

        private void Form1_Load(object sender, EventArgs e)
        {
            LoadSettings();            

        }

        private ConfigFile cf;
        private string lastFolder = null;
        private Regex regex = new Regex(@"(\dx\d\d)|(S\d\dE\d\d)", RegexOptions.Compiled | RegexOptions.IgnoreCase | RegexOptions.Singleline);
        private void LoadSettings()
        {
            if (Environment.GetCommandLineArgs().Length > 1)
            {
                FolderCombo.Text=  Environment.GetCommandLineArgs()[1];
                AddRecentDirectory(FolderCombo.Text);

            }
            cf = new ConfigFile();
            String[] recentFolders = cf.GetAllValues("RecentFolder");
            if (recentFolders!= null)
            {
                FolderCombo.Items.AddRange(recentFolders);
            }
            String[] recentText = cf.GetAllValues("RecentText");
            if (recentText!= null)
            {
                FindText.Items.AddRange(recentText);
            }
            frequentReplacements.Load();
        }

        ListBox FileList
        {
            get
            {
                return listBox1;
            }
        }

     
        private void DoLoad(object sender, EventArgs e)
        {

            LoadFiles();
        }

        private void LoadFiles()
        {
            try
            {
                if (string.IsNullOrEmpty(FolderCombo.Text))
                    return;
                FileList.Items.Clear();
                lastFolder = FolderCombo.Text;
                DirectoryInfo di = new DirectoryInfo(lastFolder);
                if (!di.Exists)
                {
                    this.statusText.Text = "El directorio no existe";
                    return;
                }
                FileInfo[] fis = di.GetFiles("*.*");
                foreach (FileInfo fi in fis)
                {
                    this.FileList.Items.Add(fi);
                }
                AddRecentDirectory(lastFolder);
                this.statusText.Text = "";
            }
            catch (Exception e)
            {
                MessageBox.Show(e.ToString());
            }
        }

        private void AddRecentDirectory(string text)
        {
            if (FolderCombo.Items.Contains(text))
                FolderCombo.Items.Remove(text);
            FolderCombo.Items.Insert(0,text);
            FolderCombo.Text= text;
        }

        private void AddTextToRemove(string text)
        {
            if (FindText.Items.Contains(text))
                FindText.Items.Remove(text);
            FindText.Items.Insert(0, text);
        }


        private void Form1_FormClosed(object sender, FormClosedEventArgs e)
        {
            SaveConfig();
        }

        private void SaveConfig()
        {
            cf.ClearElements("RecentFolder");
            foreach (String item in FolderCombo.Items)
            {
                cf.AddValue("RecentFolder" ,  item);
            }

            cf.ClearElements("RecentText");
            foreach (String item in FindText.Items)
            {
                cf.AddValue("RecentText", item);
            }
            
            cf.Save();
        }

        private void FileList_MouseDoubleClick(object sender, MouseEventArgs e)
        {
            string nombre= null, extension= null;
            if (FileList.SelectedIndex < 0)
                return;
            //SeparaNombreExtension(FileList.SelectedItem.ToString(), ref nombre, ref extension);
            string prefijo = BuscaNombreSerie(FileList.SelectedItem.ToString());
            if (string.IsNullOrEmpty (prefijo))
            {
                SeparaNombreExtension(FileList.SelectedItem.ToString(), ref nombre, ref extension);
                FindText.Text = nombre;
            }
            else
                FindText.Text = prefijo;
        }

        private string BuscaNombreSerie(string fileName)
        {
            Match match = regex.Match(fileName);
            if (match.Success)
            {
                string nombre = fileName.Substring(0, match.Index);
                return nombre;
            }
            else
                return null;
        }

        private void selectAll_Click(object sender, EventArgs e)
        {
            for (int i = 0; i < FileList.Items.Count; i++ )
                FileList.SetSelected(i, true);
            
        }
        
        private void selectNone_Click(object sender, EventArgs e)
        {
            FileList.SelectedItems.Clear();
        }

       

        private void Preview_Click(object sender, EventArgs e)
        {
            ShowPreview();
        }

        

        private void ShowPreview()
        {
            RenombraFicheros(true, false);
        }

        private void Renombra_Click(object sender, EventArgs e)
        {
            AddTextToRemove(FindText.Text);
            RenombraFicheros(false, false);
        }

        private void RenombraFicheros(bool onlyPreview, bool applyFrequent)
        {
            RenamedFileList.Items.Clear();
            progressBar.Visible = true;
            //progressBar.Maximum = FileList.Items.Count;
            ListBox.SelectedIndexCollection selectedIndices;
            selectedIndices = FileList.SelectedIndices;
            progressBar.Maximum = selectedIndices.Count;
            
            //for (int i = 0; i < FileList.Items.Count; i++ )                
            for (int i = 0; i < selectedIndices.Count; i++)                
            {                
                FileInfo fileInfo = (FileInfo) FileList.Items[selectedIndices[i]];
                String nombreOriginal = fileInfo.Name;
                string extension= "", nombre= "";
                SeparaNombreExtension(nombreOriginal, ref nombre, ref extension);
                String nuevoNombre = RenombraFichero(nombre, applyFrequent) + "." + extension;
                //RenamedFileList.Items.Add(nuevoNombre);
                string fullNewName = fileInfo.DirectoryName+ "\\"  + nuevoNombre;
                if (!onlyPreview)
                    File.Move(fileInfo.FullName,fullNewName);
                RenamedFileList.Items.Add(nuevoNombre);
                progressBar.PerformStep();
            }
            progressBar.Visible = false;
            if (!onlyPreview)
                LoadFiles();
        }

        private void SeparaNombreExtension(string nombreOriginal, ref string nombre, ref string extension)
        {
            
            int indice = nombreOriginal.LastIndexOf('.');
            if (indice > 0)
            {
                nombre = nombreOriginal.Substring(0, indice);
                extension = nombreOriginal.Substring(indice + 1);
            }
            else
            {
                nombre = nombreOriginal;
            }
            
        }

        

        private String RenombraFichero(String nombreOriginal, bool applyFrequent)
        {
            String nuevoNombre= nombreOriginal ;
            if (!applyFrequent)
            {
                if (!string.IsNullOrEmpty(FindText.Text))
                    nuevoNombre = nombreOriginal.Replace(FindText.Text, ReplaceText.Text);
            }
            else
            {
                nuevoNombre = frequentReplacements.Apply(nombreOriginal);
            }
            if (quitarCorchetes.Checked)
            {
                nuevoNombre = LimpiarConRegex(@"\[[^\[]*\]", nuevoNombre);
            }
            if (quitarParentesis.Checked)
            {
                nuevoNombre = LimpiarConRegex(@"\([^\(]*\)", nuevoNombre);
            }
            if (quitarLlaves.Checked)
            {
                nuevoNombre = LimpiarConRegex(@"\{[^\{]*\}", nuevoNombre);
            }
            if (quitarGuiones.Checked)
            {
                
                nuevoNombre = nuevoNombre.Trim(" -".ToCharArray());;
            }
            return nuevoNombre;
        }

        private string LimpiarConRegex(string exprRegex,string nuevoNombre)
        {
 	        Regex regex = new Regex(exprRegex, RegexOptions.IgnoreCase|RegexOptions.Singleline);
            string output= regex.Replace(nuevoNombre, "");
            return output;
        }

        private void browse_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog dialog=  new FolderBrowserDialog();
            dialog.RootFolder= Environment.SpecialFolder.Desktop;
            if (FolderCombo.Text != "")
                dialog.SelectedPath = FolderCombo.Text;
            if (dialog.ShowDialog() == DialogResult.OK)
            {
                FolderCombo.Text = dialog.SelectedPath;
                AddRecentDirectory(FolderCombo.Text);
                LoadFiles();

            }
        }
        
        private void FolderCombo_SelectedIndexChanged(object sender, EventArgs e)
        {
            if (lastFolder != FolderCombo.Text)
                LoadFiles();
        }

        private void button2_Click(object sender, EventArgs e)
        {
            string nuevoNombre = LimpiarConRegex(@"\[[^\[]*\]", "True Blood 1x03 Mine [HDTV-0TV] (SubTS) [otro].srt");
        }

        private void listBox1_SelectedIndexChanged(object sender, EventArgs e)
        {

        }

        private void AddToFrequent_Click(object sender, EventArgs e)
        {
            frequentReplacements.Add(FindText.Text, ReplaceText.Text);
            frequentReplacements.Save();
        }

        private void ApplyFrequent_Click(object sender, EventArgs e)
        {
            RenombraFicheros(PreviewCheck.Checked, true);
        }

        
    }
}